<template>
  <Container class="card-edit">
    <div class="container-header title title-center" slot="header">{{id ? form.name : '添加溢价'}}
      <Button
        size="large"
        class="fl btn-back"
        icon="ios-arrow-back"
        @click="$router.back()"
      >返回</Button>
    </div>
    <div class="bg-light mt pb">
      <Tabs v-model="tab" @on-click="onTabClick">
        <div class="item" slot="extra">
          <Button size="large" class="item" type="primary" icon="md-add" @click="onAdd">新建溢价策略</Button>
        </div>
        <TabPane label="基础信息" name="tab1">
          <Form :model="form" :rules="rules" :label-width="120" ref="form">
            <FormItem label="策略名称" prop="name" class="wp40">
              <Input v-model="form.name" :maxlength="50"/>
            </FormItem>
            <FormItem label="说明" class="wp40">
              <Input type="textarea" v-model="form.description" :autosize="{minRows: 2,maxRows: 5}" />
            </FormItem>
            <FormItem label="是否启用">
              <Checkbox label="是否启用" v-model="form.isEnabled"/>
            </FormItem>
            <FormItem label="溢价规则">
              <p>1、起步价与起步时间：</p>
              <p>1)起步公里数和起步时间未超出仅收起步价，</p>
              <p>2)超出的起步公里数按公里单价收费；</p>
              <p>3）超出起步的时间按时间增收服务费（从车主预约时间起，门店到车主下单地的地图推算的时间-起步时间，超出的时间在日间/夜间的时间按分钟增收服务费），起步公里与起步时间都超过按各自规则收费；不收费请填0；</p>
              <p>2、起步公里数与公里单价：用户下单地址离门店的路线公里数，在起步公里数内仅收起步价；超出的起步公里数外的公里数以公里单价计费；不收费请填0；</p>
              <p>3、设置夜间服务时间和夜间服务费的，1）按分钟收费，根据路线公里数推算出门店到用户下单地的时间，使用了日间/夜间服务时间的每分钟增收夜间服务费；2）按次数收费，预约时间在日间或夜间按次增收服务费；</p>
              <p>4、非夜间服务费：夜间服务时间以外的时间为非夜间服务时间，门店到达车主下单地所用的时间-触发溢价策略且在非夜间服务时间内的，按每分钟增收服务费，起步时间是指设置的起步时间内不收非夜间服务费；不收费请填0；</p>
              <p>5、长途阀值(km)与长途溢价(km)：设置长途公里数的，用户下单地离门店距离未超出长途阀值不增收长途费；超出的公里数按每公里增收长途费用；如设置了10公里为长途阀值，超出10公里以外的公里数增收长途溢价；</p>
              <p>6、一个溢价策略可设置多个不同的服务项目，不同溢价策略可设置相同服务项目；结算时自动取有效状态且最新创建的溢价策略计算；</p>
              <p>7、订单的实付金额：服务项目价+溢价起步价+超出起步公里数的公里数*公里单价+超出起步时间的时间*非/夜间服务时间分钟+超出长途阀值的公里数*长途公里单价；</p>
              <p>8、订单计算金额时使用当前服务项目关联最新创建时间+启用状态的一条溢价规则计算订单；</p>
              <p>【举例1】：</p>
              <p>如：上门搭电服务价50元，溢价起步价5元，起步时间15分钟，起步公里数5km，公里单价2元，夜间服务时间为22：00-05：00，夜间每分钟2元，非夜间每分钟1元，</p>
              <p>假设用户下单地址离门店为6km、20分钟，下单预约时间为21：50，门店到达用户下单地址需要20分钟，（预约时间往前算，15分钟内不收费，超出的5分钟在日间收取每分钟服务费），此单收费是服务费单价50元+溢价起步价5元+超出1公里2元+用了5分钟的日间服务费5元，本单共计62元；</p>
              <p>如：长途阀值设为4公里，长途溢价3元/公里，那么6公里中有1公里算长途，那么此单62+3共65元；</p>
              <p>如：设置非夜间按次收费10元，夜间按次收费20元，因预约时间在日间，此单收费，项目服务价50元+溢价起步价5元+超出1公里2元+日间服务费10元+长途费3元，共计70元；</p>
            </FormItem>
          </Form>
        </TabPane>
        <TabPane label="溢价策略" name="tab2" class="scroll">
          <Table
          :height="options.tableHeight"
          stripe
          :columns="list.columns"
          :data="list.data"
          no-data-text="亲，没有找到相关记录哦！~"></Table>
        </TabPane>
      </Tabs>
    </div>
    <Loader :status="status" @refresh="getData"></Loader>
    <div class="container-footer bg-white" slot="footer">
      <Button size="large" class="fr btn-back" type="primary" @click="onSave">保存</Button>
    </div>
  </Container>
</template>
<script>
import table from '@/table'
import PremiumEditData from './list/PremiumEditData'
export default {
  data() {
    const validateName = (rule, value, callback) => {
      if (value.trim() === '') {
        callback(new Error('请输入策略名称'))
      } else {
        if (value.length < 2) {
          callback(new Error('溢价名称长度不能小于2并且不能大于50'))
        } else {
          callback()
        }
      }
    }
    return {
      id: this.$route.query.id || '',
      status: 'pass',
      list: PremiumEditData,
      options: {
        tableHeight: 300
      },
      isRepeat: false,
      isChange: false,
      allType: [],
      categoryId: '',
      storeServerId: '',
      longDistance: null,
      startNumber: null,
      form: {
        name: '',
        description: '',
        isEnabled: true,
        status: '',
        itemList: [{
          premiumId: '',
          startFee: '',
          startNumber: '',
          perKilometreFee: '',
          darkStartTime: '',
          darkEndTime: '',
          startTime: '',
          darkServerFee: '',
          serverFee: '',
          longDistance: '',
          longDistanceFee: '',
          perKilometreFee: '',
          storeServerId: '',
          payType: ''
        }]
      },
      rules: {
        name: [{ validator: validateName, trigger: 'blur', required: true }]
      }
    }
  },
  mounted() {
    this.initTable()
    this.$bus.$on('onChangeNum', ({ row, index }) => this.onChangeNum(row, index))
    this.$bus.$on('onDelete', ({ id, index }) => this.onDelete(id, index))
    if (this.id) {
      this.getData()
    } else {
      this.getType()
      this.list.data = []
      this.list.data.push({
        startFee: 0,
        startNumber: 0,
        perKilometreFee: 0,
        darkStartTime: '00:00',
        darkEndTime: '00:00',
        darkServerFee: 0,
        serverFee: 0,
        longDistance: 0,
        longDistanceFee: 0,
        perKilometreFee: 0,
        categoryId: null,
        payType: '',
        startTime: 0,
        allType: []
      })
    }
  },
  destroyed() {
    this.$bus.$off()
  },
  methods: {
    ...table,
    getData() {
      this.status = 'loading'
      this.$ajaxGet('/server/server_premium/detail/' + this.id).then(data => {
        this.form.name = data.name
        this.form.description = data.description
        this.form.isEnabled = data.isEnabled
        this.list.data = (data.itemList || []).map(item => {
          return {
            premiumId: item.premiumId,
            startFee: item.startFee,
            startNumber: item.startNumber,
            perKilometreFee: item.perKilometreFee,
            darkStartTime: this.completIng(4, '0', item.darkStartTime).split(''),
            darkEndTime: this.completIng(4, '0', item.darkEndTime).split(''),
            darkServerFee: item.darkServerFee,
            serverFee: item.serverFee,
            longDistance: item.longDistance,
            longDistanceFee: item.longDistanceFee,
            storeServerId: item.storeServerId,
            payType: item.payType,
            startTime: item.startTime,
            allType: []
          }
        })
        this.getType()
        this.list.data.forEach(item => {
          item.darkStartTime.splice(2, 0, ':')
          let start = item.darkStartTime.join('')
          item.darkStartTime = start
          item.darkEndTime.splice(2, 0, ':')
          let end = item.darkEndTime.join('')
          item.darkEndTime = end
        })
        this.backTableTop()
        this.status = 'pass'
      }).catch(()=> {
        this.status = 'error'
      })
    },
    getType() {
      let param = {
        typeEnum: 'SERVER_VISIT',
      }
      this.$ajaxGet('/server/store_server/list_type', param).then(data => {
        this.allType = (data || []).map(item => {
          return {
            categoryId: item.id,
            name: item.name
          }
        })
        this.list.data.forEach(item => {
          this.$set(item, 'allType', this.allType)
        })
      })
    },
    onChangeNum(row, index) {
      this.longDistance = row.longDistance
      this.startNumber = row.startNumber
      this.isRepeat = false
      this.isChange = true
      this.list.data[index] = row
      this.storeServerId = row.storeServerId
      if (this.list.data.length > 1) {
        this.isRepeat = this.list.data.some((item, i) => item.storeServerId == this.storeServerId && index !== i)
        if (this.isRepeat) {
          this.$Notice.error({
            title: '请选择不同的服务项目'
          })
        }
      }
    },
    onAdd() {
      if ((this.list.data[this.list.data.length - 1]).storeServerId == undefined) {
        this.$Notice.error({
          title: '请选择服务项目'
        })
        return
      }
      this.list.data.push({
        startFee: 0,
        startNumber: 0,
        perKilometreFee: 0,
        darkStartTime: '00:00',
        darkEndTime: '00:00',
        darkServerFee: 0,
        serverFee: 0,
        longDistance: 0,
        longDistanceFee: 0,
        perKilometreFee: 0,
        categoryId: null,
        payType: 'MINUTE',
        startTime: 0,
        allType: this.allType
      })
    },
    onDelete(id, index) {
      if (this.list.data.length > 1) {
        this.$Modal.confirm({
          title: '删除',
          content: '确定删除当前溢价策略？',
          loading: true,
          onOk: () => {
            this.$Notice.success({
              title: '删除成功'
            })
            this.list.data.splice(index, 1)
            this.$Modal.remove()
          }
        })
      } else {
        this.$Notice.error({
          title: '至少得留一个吧'
        })
      }

    },
    onSave() {
      if (this.isRepeat) {
        this.$Notice.error({
          title: '请选择不同的服务项目'
        })
      }
      if (this.isChange && this.longDistance <= this.startNumber) {
        this.$Notice.error({
          title: '长途阀值必须大于起步公里数'
        })
        return
      }
      if (this.status === 'loading' || this.isRepeat) return
      this.$refs.form.validate(valid => {
        if (valid) {
          let text = this.id ? '编辑' : '新增'
          let url = '/server/server_premium/save'
          let newArr = (this.list.data || []).filter(item => {
            return item.storeServerId
          }).map(item => {
            return {
              ...item,
              darkStartTime: parseInt(item.darkStartTime.replace(new RegExp(/(:)/g), '')),
              darkEndTime: parseInt(item.darkEndTime.replace(new RegExp(/(:)/g), ''))
            }
          })
          let param = {
            name: this.form.name,
            description: this.form.description,
            isEnabled: this.form.isEnabled,
            itemList: newArr
          }
          if (this.id) param.id = this.id
          this.status = 'loading'
          this.$jsonPost(url, param).then(data => {
            this.$Notice.success({
              title: text + '成功'
            })
            this.$router.push('/product/premium/list')
          })
        } else {
          this.$Notice.error({
            title: '请填写基础信息'
          })
        }
      })
    },
    completIng(bits, identifier, value) {
      value = Array(bits + 1).join(identifier) + value
      return value.slice(-bits)
    }
  }
}
</script>
